package unitTool;

import com.wangmei.model.Categery;

import java.util.*;

public class CategeryTree {
    public static List<Map<String,Object>> changeToTree(List<Categery>  categerys){
        //根据 pid排序
        sort(categerys);
        List<Map<String,Object>> reList = new ArrayList<>();

        Map<Integer, Object> dic = new HashMap<>();
        for(Categery ca :categerys){
            //根节点
            if(ca.getPid()==0) {
                Map<String,Object> head = new LinkedHashMap<>();
                head.put("text", ca.getCname());
                head.put("cid",ca.getCid());
                dic.put(ca.getCid(),head);
                //id
                reList.add(head);
            }
            else{
                //子节点
                int pid = ca.getPid();
                String cname=ca.getCname();
                //封装儿子
                Map<String,Object> child = new LinkedHashMap<>();
                child.put("text",cname);
                child.put("cid",ca.getCid());
                //添加到字典
                dic.put(ca.getCid(),child);
                //找到父亲
                Map map = (Map) dic.get(pid);
                //将儿子放入父亲里
                List<Map<String,Object>> tree = (List) map.get("tree");
                if(tree == null) {
                    tree = new ArrayList();
                    map.put("nodes",tree);
                }
                tree.add(child);
            }
        }
        return reList;
    }
    public static void sort(List<Categery> categerys){
        Collections.sort(categerys, new Comparator<Categery>() {
            @Override
            public int compare(Categery o1, Categery o2) {
                return o1.getPid()-o2.getPid();
            }
        });
    }
}
